package com.apise.search;

import org.ansj.domain.Term;
import org.ansj.splitWord.analysis.ToAnalysis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.stream.Collectors;

@Controller
public class QueryController {
    private final ResultBuilder resultBuilder;
    private final DatabaseMapper mapper;

    @Autowired
    public QueryController(ResultBuilder resultBuilder, DatabaseMapper mapper) {
        this.resultBuilder = resultBuilder;
        this.mapper = mapper;
        ToAnalysis.parse("预热分词");
    }

    @GetMapping("/web")
    public String query(String query, @RequestParam(value = "page", required = false) String pageStr, Model model) {
        if (query == null) {
            return "redirect:/index.html";
        }

        query = query.trim();
        if (query.isEmpty()) {
            return "redirect:/index.html";
        }

        int limit = 20;
        int offset = 0;
        int page = 1;
        if (pageStr != null) {
            try {
                page = Integer.parseInt(pageStr);
                offset = (page - 1) * limit;
            } catch (NumberFormatException ignored) {}
        }

        List<String> queryList = ToAnalysis.parse(query)
                .getTerms()
                .stream()
                .parallel()
                .map(Term::getName)
                .filter(s -> !s.trim().isEmpty())
                .collect(Collectors.toList());

        if (queryList.isEmpty()) {
            return "redirect:/index.html";
        }

        query = queryList.get(0);
        final String word = query;

        List<Result> resultList = mapper.query(query, offset, limit)
                .stream()
                .parallel()
                .map(doc -> resultBuilder.build(doc, word))
                .collect(Collectors.toList());

        model.addAttribute("query", query);
        model.addAttribute("docList", resultList);
        model.addAttribute("page", page);

        return "query";
    }
}
